package com.ic.es.service.impl;

import com.IC.domain.vo.AccessControlRecordVO;
import com.alibaba.fastjson2.JSONObject;
import com.ic.es.service.EsAccessRecordService;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.YearMonth;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
public class EsAccessRecordServiceImpl implements EsAccessRecordService {

    private final RestHighLevelClient client;
    private static final String INDEX_PREFIX = "index_entrance_guard_";
    private static final String ALIAS_NAME = "entrance_guard_data";

    @Autowired
    public EsAccessRecordServiceImpl(RestHighLevelClient client) {
        this.client = client;
    }

    @Override
    public void bulkRecords(List<AccessControlRecordVO> records) {
        String indexName = getIndexName();
        BulkRequest bulkRequest = new BulkRequest();
        records.forEach(record  -> {
            bulkRequest.add(
                    new IndexRequest(indexName)
                            .id(record.getId()+"")
                            .source(JSONObject.toJSONString(record), XContentType.JSON));
        });
        try {
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.info("添加商品信息到ES错误，商品信息：{}，异常：{}",JSONObject.toJSONString(records),e);
        }
    }

    @Override
    public void delete() {

    }

    @Override
    public void bulkList(List<Map> records) {
        String indexName = getIndexName();
        BulkRequest bulkRequest = new BulkRequest();
        records.forEach(record  -> {
            bulkRequest.add(
                    new IndexRequest(indexName)
                            .id(record.get("id")+"")
                            .source(JSONObject.toJSONString(record), XContentType.JSON));
        });
        try {
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.info("添加商品信息到ES错误，商品信息：{}，异常：{}",JSONObject.toJSONString(records),e);
        }

    }


    /**
     * 创建新的索引并设置别名。
     */
    @Override
    public void createNewIndex() {

        try {
            // 生成新索引的名称
            String newIndexName = getIndexName();

            // 创建新索引
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(newIndexName);
            // ... 可以设置索引的mappings和settings
            CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);

            if (createIndexResponse.isAcknowledged()) {
                // 更新别名，这里为了简化，我们假设不需要移除旧索引的别名（在实际应用中你可能需要这样做）
                IndicesAliasesRequest aliasesRequest = new IndicesAliasesRequest();
                // 添加新索引的别名
                aliasesRequest.addAliasAction(IndicesAliasesRequest.AliasActions.add().index(newIndexName).alias(ALIAS_NAME));

                // 发送别名更新请求
                client.indices().updateAliases(aliasesRequest, RequestOptions.DEFAULT);

                System.out.println("New index created and alias updated successfully: " + newIndexName);
            } else {
                System.out.println("Failed to create new index.");
            }
        } catch (IOException e) {
            // 处理异常，例如记录日志或进行其他错误处理
            System.err.println("Error creating new index or updating alias: " + e.getMessage());
            // 如果需要，可以在这里抛出运行时异常
            // throw new RuntimeException("Failed to create index or update alias", e);
        }

    }


    /**
     * 定时任务，每月执行一次，创建新索引。
     */
    @Scheduled(cron = "0 0 0 1 * ?") // 每月的第一天凌晨0点执行
    public void scheduleCreateNewIndex() {
        createNewIndex();
    }

    /**
     * 获取当前索引名称，格式为"index_entrance_guard_yyyyMM"，例如"indexface-202408"。
     *
     * @return 当前索引名称
     */
    private String getIndexName() {
        return INDEX_PREFIX + YearMonth.now().toString().replace("_", "");
    }

}
